using SG3L_RAG.Application.DTOs;
using SG3L_RAG.Application.Interfaces;
using SG3L_RAG.Domain.Entities;

namespace SG3L_RAG.Application.Services;

/// <summary>
/// 认证服务实现
/// </summary>
public class AuthService : IAuthService
{
    private readonly IUserService _userService;
    private readonly IJwtService _jwtService;

    public AuthService(IUserService userService, IJwtService jwtService)
    {
        _userService = userService;
        _jwtService = jwtService;
    }

    public async Task<LoginResponseDto?> LoginAsync(LoginDto loginDto)
    {
        try
        {
            // 验证用户凭据
            var user = await ValidateUserAsync(loginDto.Username, loginDto.Password);
            if (user == null)
                return null;

            // 生成JWT Token
            return await _jwtService.GenerateTokenAsync(user);
        }
        catch (Exception)
        {
            return null;
        }
    }

    public async Task<LoginResponseDto> RegisterAsync(RegisterDto registerDto)
    {
        try
        {
            // 检查用户名是否已存在
            var existingUserByUsername = await _userService.GetByUsernameAsync(registerDto.Username);
            if (existingUserByUsername != null)
                throw new InvalidOperationException("用户名已存在");

            // 检查邮箱是否已存在（仅当邮箱不为空时检查）
            if (!string.IsNullOrWhiteSpace(registerDto.Email))
            {
                var existingUserByEmail = await _userService.GetByEmailAsync(registerDto.Email);
                if (existingUserByEmail != null)
                    throw new InvalidOperationException("邮箱已存在");
            }

            // 创建新用户
            var newUser = await _userService.CreateAsync(
                registerDto.Username, 
                registerDto.Password, 
                registerDto.Email, 
                registerDto.PhoneNumber, 
                registerDto.Role);

            // 转换为DTO
            var userDto = new UserInfoDto
            {
                Id = newUser.Id,
                Username = newUser.Username,
                Email = newUser.Email,
                Role = newUser.Role,
                PhoneNumber = newUser.PhoneNumber,
                Avatar = newUser.Avatar, // 添加Avatar字段
                CreatedAt = newUser.CreatedAt
            };

            // 生成JWT Token
            return await _jwtService.GenerateTokenAsync(userDto);
        }
        catch (Exception)
        {
            throw;
        }
    }

    public async Task<UserInfoDto?> ValidateUserAsync(string username, string password)
    {
        try
        {
            // 根据用户名获取用户
            var user = await _userService.GetByUsernameAsync(username);
            if (user == null)
                return null;

            // 验证密码
            if (!user.CheckPassword(password))
                return null;

            // 转换为DTO并返回
            return new UserInfoDto
            {
                Id = user.Id,
                Username = user.Username,
                Email = user.Email,
                Role = user.Role,
                PhoneNumber = user.PhoneNumber,
                Avatar = user.Avatar, // 添加Avatar字段
                CreatedAt = user.CreatedAt
            };
        }
        catch (Exception)
        {
            return null;
        }
    }
}
